package web.log;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class LoggerFactory {
	
	private static Logger newsLogger;
	private static Logger emailLogger;
	
	public static Logger initNewsLogger() {
		if(newsLogger==null){
			newsLogger = Logger.getLogger("Userlog");
		}
		return newsLogger;
	}
	
	public static Logger initEmailLogger() {
		if(emailLogger==null){
			emailLogger = Logger.getLogger("emailLog");
		}
		return emailLogger;
	}

    /**
     * 写日志文件
     * @param t
     * @return
     */
	public static String getTrace(Throwable t) {
		StringWriter stringWriter = new StringWriter();
		PrintWriter writer = new PrintWriter(stringWriter);
		t.printStackTrace(writer);
		try {
			stringWriter.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		StringBuffer buffer = stringWriter.getBuffer();
		return buffer.toString();
	}

	/**
	 * @param t
	 */
	public static void exception2File(Throwable t) {
		newsLogger.error(getTrace(t));
		emailLogger.error(getTrace(t));
	}
	

	public static void main(String[] args) {
		Logger logger = Logger.getLogger("wei");
		logger.info("chao");
		logger.warn("wei");
		logger.error("weichao");

		try {
			System.arraycopy(new byte[2], 0, new byte[1], 0, 2);
		} catch (Exception e) {
			logger.error(LoggerFactory.getTrace(e));
			e.printStackTrace();
		}
	}
}
